﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.IO;

using System.Xml.Serialization;
using System.Xml;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


namespace common
{
    public class MSMQHelper:IDisposable
    {
        #region 成员
        private string path;
        #endregion

        #region 构造函数
        public MSMQHelper(string path)
        {
            this.path = System.Configuration.ConfigurationManager.AppSettings[path].ToString();
        }
        #endregion

        #region 接收消息
        /// <summary>
        /// 接收来自MSMQ消息队列数据
        /// </summary>
        /// <param name="type">实例的类型 用于反序列化</param>
        /// <returns>System.Messaging.Message的实例</returns>
        public System.Messaging.Message ReceiveObject()
        {
            System.Messaging.Message msg=null;
            try
            {
                //判读远程计算机队列 需要域控制器
                //if (MessageQueue.Exists(path))
                {
                    using (MessageQueue queue = new MessageQueue(path, QueueAccessMode.Receive))
                    {
                        msg = queue.Receive(new TimeSpan(0,0,10));
                        return msg;
                    }
                }
            }
            catch
            {
                return msg;
            }
        }
        #endregion

        #region 发送消息
        /// <summary>
        /// 发送消息到队列
        /// </summary>
        /// <param name="lable">leibel值</param>
        /// <param name="sobj">body值</param>
        public void SendObject(string lable, object sobj)
        {
            try
            {
                //判读远程计算机队列 需要域控制器
                //if (!MessageQueue.Exists(path))
                //    MessageQueue.Create(path);

                using (MessageQueue queue = new MessageQueue(path, QueueAccessMode.Send))
                {
                    System.Messaging.Message msg = new System.Messaging.Message();
                    msg.Label = lable;
                    //string temstr = objSerializerToString(sobj);
                    msg.Body = sobj;
                    //msg.Formatter = new XmlMessageFormatter(new Type[] { sobj.GetType() });
                    msg.Formatter = new ActiveXMessageFormatter();
                    queue.Send(msg, MessageQueueTransactionType.None);
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 重载SendObject方法。 用于将字符串写入到消息队列。MO上行时调用。
        /// </summary>
        /// <param name="lable"></param>
        /// <param name="sobj"></param>
        /// <param name="a">标记位 确定是重载。</param>
        public void SendObject(string lable, object sobj,string a)
        {
            try
            {
                //判读远程计算机队列 需要域控制器
                //if (!MessageQueue.Exists(path))
                //    MessageQueue.Create(path);

                using (MessageQueue queue = new MessageQueue(path, QueueAccessMode.Send))
                {
                    System.Messaging.Message msg = new System.Messaging.Message();
                    msg.Label = lable;
                    //string temstr = objSerializerToString(sobj);
                    msg.Body = sobj.ToString();
                    //msg.Formatter = new XmlMessageFormatter(new Type[] { sobj.GetType() });
                    msg.Formatter = new ActiveXMessageFormatter();
                    queue.Send(msg, MessageQueueTransactionType.None);
                }
            }
            catch
            {
                //System.Diagnostics.Debug.WriteLine(ex);
            }
        }
        #endregion

        #region 序列化
        /// <summary>
        /// 将对象序列化成字符串返回.
        /// </summary>
        /// <param name="obj">序列化的实例</param>
        /// <returns>返回系列化后的XML字符串</returns>
        public static string objSerializerToString(object obj)
        {
            XmlSerializer xs = new XmlSerializer(obj.GetType());
            MemoryStream ms = new MemoryStream();
            XmlTextWriter xtw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
            xtw.Formatting = Formatting.Indented;
            xs.Serialize(xtw, obj);
            ms.Seek(0, SeekOrigin.Begin);
            StreamReader sr = new StreamReader(ms);
            string str = sr.ReadToEnd();
            xtw.Close();
            ms.Close();
            return str;
        }

        /// <summary>
        /// 将字符串反序列化成类对象
        /// </summary>
        /// <param name="XMLstr"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object StringSerializerToObj(string XMLstr,Type type)
        {
            XmlSerializer xs = new XmlSerializer(type);
            StringReader sr = new StringReader(XMLstr);
            object obj = xs.Deserialize(sr);
            return obj;
        }
        #endregion

        #region 释放内存
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(true);
        }

        protected virtual void Dispose(bool disposing)
        {

        }
        #endregion
    }
}
